import { defineStore } from 'pinia'

const STORE_KEY = 'playControl'
const usePlayControl = defineStore(STORE_KEY, {
  state: () => ({
    playMode: 'auto', // 播放模式 单次 single / 自动 auto
    intervals: [],
    zeroSpanInterval: null,
    playbackRate: 1000,
    cycleStart: 0
  }),
  getters: {},
  actions: {
    add(interval) {
      this.intervals.push(interval)
    },
    del(interval) {
      const index = this.intervals.findIndex(item => item === interval)
      this.intervals.splice(index, 1)
    },
    clear() {
      this.intervals = []
    },
    switch(mode) {
      this.playMode = mode
    },
    single() {
      if (this.playMode === 'auto') {
        this.switch('single')
        this.intervals.forEach(item => {
          item.pause()
          item.next()
        })
        return
      }
      this.intervals.forEach(item => {
        item.next()
      })
    },
    auto() {
      if (this.mode === 'auto') {
        return
      }
      this.switch('auto')
      this.intervals.forEach(item => {
        item.play()
      })
    },
    setPlaybackRate(val) {
      this.playbackRate = val
      this.restartInterval()
    },
    restartInterval() {
      this.intervals.forEach(interval => {
        if (interval.destroyed) {
          return
        }
        interval.pause()
        interval.play()
      })
    }
  }
})

export default usePlayControl
